<template>
  <div class="pagination-container">
    <ElPagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="pageSizes"
      :layout="layout"
      :total="total"
      :background="background"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
  interface PaginationProps {
    /** 总条目数 */
    total: number
    /** 当前页码 */
    page?: number
    /** 每页显示条数 */
    limit?: number
    /** 每页显示个数选择器的选项设置 */
    pageSizes?: number[]
    /** 组件布局 */
    layout?: string
    /** 是否为分页按钮添加背景色 */
    background?: boolean
  }

  const { page, limit, pageSizes, layout, background } = withDefaults(
    defineProps<PaginationProps>(),
    {
      page: 1,
      limit: 10,
      pageSizes: () => [10, 20, 30, 50],
      layout: 'total, sizes, prev, pager, next, jumper',
      background: true,
    },
  )

  const emit = defineEmits<{
    /** 页码改变时触发 */
    (e: 'update:page', page: number): void
    /** 每页显示条数改变时触发 */
    (e: 'update:limit', limit: number): void
    /** 分页改变时触发 */
    (e: 'pagination', params: { page: number; limit: number }): void
  }>()

  // 当前页码
  const currentPage = ref(page)
  // 每页条数
  const pageSize = ref(limit)

  // 监听属性变化
  watch(
    () => page,
    newVal => {
      currentPage.value = newVal
    },
  )

  watch(
    () => limit,
    newVal => {
      pageSize.value = newVal
    },
  )

  // 每页显示条数改变时触发
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    emit('update:limit', val)
    emit('pagination', {
      page: currentPage.value,
      limit: val,
    })
  }

  // 当前页改变时触发
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    emit('update:page', val)
    emit('pagination', {
      page: val,
      limit: pageSize.value,
    })
  }
</script>

<style scoped>
  .pagination-container {
    padding: 15px 0;
    display: flex;
    justify-content: flex-end;
  }
</style>
